﻿#include "baiduface.h"
#include <QNetworkReply>
#include <QUrlQuery>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>

BaiduFace::BaiduFace(const QString& appkey, const QString& secret, QObject *parent)
    : QObject(parent), _appkey(appkey), _secret(secret)
{
    _client = new QNetworkAccessManager(this);
    getToken();
}

void BaiduFace::getToken()
{
    QUrlQuery params;
    params.addQueryItem("grant_type", "client_credentials");
    params.addQueryItem("client_id", _appkey);
    params.addQueryItem("client_secret", _secret);

    QNetworkRequest request(QUrl("https://aip.baidubce.com/oauth/2.0/token"));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

    _client->post(request, params.toString(QUrl::FullyEncoded).toUtf8());
    connect(_client, &QNetworkAccessManager::finished, this, &BaiduFace::on_tokenReply);
}

void BaiduFace::on_tokenReply(QNetworkReply* reply)
{
    QJsonObject json = QJsonDocument::fromJson(reply->readAll()).object();
    _token = json["access_token"].toString();
    disconnect(_client, &QNetworkAccessManager::finished, this, &BaiduFace::on_tokenReply);
    reply->deleteLater();
}

void BaiduFace::search(const QByteArray face, const QString groups)
{
    _uid.clear();

    QUrlQuery params;
    params.addQueryItem("access_token", _token);
    QUrl api("https://aip.baidubce.com/rest/2.0/face/v3/search");
    api.setQuery(params);

    QJsonObject body;
    body["image"] = QString(face.toBase64());
    body["image_type"] = "BASE64";
    body["group_id_list"] = groups;
    QJsonDocument data(body);

    QNetworkRequest request(api);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    connect(_client, &QNetworkAccessManager::finished, this, &BaiduFace::on_searchReply);

    _client->post(request, data.toJson());
}

void BaiduFace::on_searchReply(QNetworkReply* reply)
{
    disconnect(_client, &QNetworkAccessManager::finished, this, &BaiduFace::on_searchReply);
    QJsonObject json = QJsonDocument::fromJson(reply->readAll()).object();

    if (json["error_code"].toInt())
    {
        qDebug() << json["error_msg"].toString();
    }
    else
    {
        QJsonObject result = json["result"].toObject();
        QJsonArray user_list = result["user_list"].toArray();
        for (int i = 0; i < user_list.size(); i++)
        {
            QJsonObject user = user_list[i].toObject();
            _uid = user["user_id"].toString();
            emit found();
        }
    }
    reply->deleteLater();
}

QString BaiduFace::userid()
{
    return _uid;
}
